<script setup>
import { ref } from 'vue'
import { addBorrowerService, editBorrowerService } from '@/api/borrower.js'
let isEdit = undefined
const dialogVisible = ref(false)
const formRef = ref()
const formModel = ref({
  username: '',
  password: '',
  nickName: ''
})
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    {
      pattern: /^\S{5,10}$/,
      message: '用户名必须是 5-10位 的非空字符',
      trigger: 'change'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15位 的非空字符',
      trigger: 'change'
    }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'change' },
    {
      pattern: /^\S{1,15}$/,
      message: '昵称必须是 1-15位 的非空字符',
      trigger: 'change'
    }
  ]
}

const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate()
  if (isEdit) {
    await editBorrowerService(formModel.value)
    ElMessage.success('编辑成功')
  } else {
    await addBorrowerService(formModel.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  emit('success')
}

// 组件对外暴露一个方法 open，基于open传来的参数，区分添加还是编辑
// open({})  => 表单无需渲染，说明是添加
// open({ id, cate_name, ... })  => 表单需要渲染，说明是编辑
// open调用后，可以打开弹窗
const open = (row) => {
  dialogVisible.value = true
  formModel.value = { ...row } // 添加 → 重置了表单内容，编辑 → 存储了需要回显的数据
  isEdit = formModel.value.username
}

// 向外暴露方法
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑读者' : '添加读者'"
    width="30%"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formModel.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formModel.password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model="formModel.nickName"
          placeholder="请输入昵称"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
